<?php //-*-coding: utf-8;-*-

// 系统执行时间
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

// 系统执行时间
function microtime_run()
{
	$StartTime = (empty($GLOBALS['StartTime'])) ? microtime_float() : $GLOBALS['StartTime'];
	$EndTime = microtime_float();
	$RunTime = $EndTime - $StartTime;
	return $RunTime;
}
//获取文件大小
function format_bytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

//路由
function router()
{
	if( PHP_SAPI === 'cli' )
	{

		// Command line requires a bit of hacking
		if( isset($_SERVER['argv'][1]) )
		{
			$current_uri = $_SERVER['argv'][1];

			// Remove GET string from segments
			if( ($query = strpos($current_uri, '?')) !== FALSE )
			{
				list($current_uri, $query) = explode('?', $current_uri, 2);

				// Parse the query string into $_GET
				parse_str($query, $_GET);
			}
		}

	} elseif ( current($_GET) === '' && substr($_SERVER['QUERY_STRING'], -1) !== '=' ) {
		// The URI is the array key, eg: ?this/is/the/uri
		$current_uri = key($_GET);

		// Remove the URI from $_GET
		unset($_GET[$current_uri]);

		// Remove the URI from $_SERVER['QUERY_STRING']
		$_SERVER['QUERY_STRING'] = ltrim(substr($_SERVER['QUERY_STRING'], strlen($current_uri)), '/&');
	} elseif ( isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] ) {
		//self::$current_uri = $_SERVER['PATH_INFO'];
		$current_uri = $_SERVER['REQUEST_URI'];
	} elseif ( isset($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] ) {
		$current_uri = $_SERVER['ORIG_PATH_INFO'];
	} elseif ( isset($_SERVER['PHP_SELF']) && $_SERVER['PHP_SELF'] ) {
		$current_uri = $_SERVER['PHP_SELF'];
	}

	$query_string = '';
	if( !empty($_SERVER['QUERY_STRING']) )
	{
		$query_string = '?'.trim($_SERVER['QUERY_STRING'], '&/');
	}

	$current_uri = preg_replace('#\.[\s./]*/#', '', $current_uri);

	$current_uri = trim($current_uri, '/');

	/***************************************************
	 * @author nitian <yangxiaolei@gamewave.net>
	 * 路由规则修改开始
	 * 修改内容：？后get参数不再计算到rewrite部分
	 ***************************************************/

	if(($pos = strpos($current_uri, '?')) !== false)
	{
		//var_dump($current_uri);
		$current_uri = substr($current_uri, 0, $pos);
		//var_dump($current_uri);exit;
	}
	$current_uri = rtrim($current_uri, '/');

	/***************************************************
	 * 路由规则修改结束
	 ***************************************************/

	$segments	= explode('/', $current_uri);

	foreach( $segments as $key=>$val ) {
		$_GET[$key] = $val;
	}
}


//入口
function action()
{
	router();

	if ( empty($_GET[0]) || $_GET[0] == 'index.php' ) $_GET[0] = 'admin';
	if( empty($_GET[1]) ) $_GET[1] = 'index';

	//$_GET = array_map('strtolower', $_GET);

	$file = CONTROLLERS_PATH . $_GET[0] . '.php';

	if( !file_exists( $file ) )
	{
		die('The server is busy, please try again later.');
	}
	$c = new $_GET[0];
	if( !method_exists( $c, $_GET[1] ) )
	{
		die('The server is busy, please try again later.');
	}
	$c->$_GET[1]();
	$c->display($c->tpl);
}

// cli入口
function cli_action()
{
	router();

	$_GET = array_map('strtolower', $_GET);

	$file = EXEC_PATH . $_GET[0] . '.php';

	if( !file_exists( $file ) )
	{
		die('The server is busy, please try again later.');
	}
	$c = new $_GET[0];
	if( !method_exists( $c, $_GET[1] ) )
	{
		die('The server is busy, please try again later.');
	}

	$c->$_GET[1]($_GET);
}

function __autoload ($class_name)
{
	if( is_file(CONTROLLERS_PATH . $class_name . '.php') )	require CONTROLLERS_PATH . $class_name . '.php';
	elseif( is_file( LIB_PATH . $class_name . '.php' ) )	require LIB_PATH . $class_name . '.php';
	elseif( is_file( EXEC_PATH . $class_name . '.php' ) )	require EXEC_PATH . $class_name . '.php';
	elseif( is_file( MODELS_PATH . $class_name. '.php') )	require MODELS_PATH . $class_name. '.php';
	elseif( is_file( MODELS_PATH . str_replace('Model','',$class_name) . '.php' ) )	require MODELS_PATH . str_replace('Model','',$class_name) . '.php';
    elseif( is_file ( VENDORS_PATH . $class_name. '.php')){ require VENDORS_PATH. $class_name . '.php';}
	elseif( is_file ( VENDORS_PATH . strtolower($class_name). '.php')){ require VENDORS_PATH. strtolower($class_name) . '.php';}
	elseif($class_name == 'model') require MODELS_PATH . ucfirst($class_name). '.php';
	else	die('no load class '.$class_name);
}

function getClientIP()
{
    if( isset($_SERVER) )
	{
		if( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) )
		{
			$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		} elseif ( isset($_SERVER["HTTP_CLIENT_IP"]) ) {
			$realip = $_SERVER["HTTP_CLIENT_IP"];
		} elseif ( isset($_SERVER["REMOTE_ADDR"]) ) {
			$realip = $_SERVER["REMOTE_ADDR"];
		} else {
			$realip = $_SERVER["SSH_CLIENT"];
		}
	} else {
		if( getenv("HTTP_X_FORWARDED_FOR") )
		{
			$realip = getenv("HTTP_X_FORWARDED_FOR");
		} elseif ( getenv("HTTP_CLIENT_IP") ) {
			$realip = getenv("HTTP_CLIENT_IP");
		} else {
			$realip = getenv("REMOTE_ADDR");
		}
    }
    return addslashes($realip);
}

//url redirect
function redirect($uri = '', $method = '302')
{
	$uri = (array) $uri;

	for ($i = 0, $count_uri = count($uri); $i < $count_uri; $i++)
	{
		if (strpos($uri[$i], '://') === FALSE)
		{
			//$uri[$i] = url::site($uri[$i]);
			$uri[$i] = $uri[$i];
		}
	}
	if ($method == '300')
	{
		if ($count_uri > 0)
		{
			header('HTTP/1.1 300 Multiple Choices');
			header('Location: '.$uri[0]);

			$choices = '';
			foreach ($uri as $href)
			{
				$choices .= '<li><a href="'.$href.'">'.$href.'</a></li>';
			}

			exit('<h1>301 - Multiple Choices:</h1><ul>'.$choices.'</ul>');
		}
	}
	else
	{
		$uri = $uri[0];

		if ($method == 'refresh')
		{
			header('Refresh: 0; url='.$uri);
		}
		else
		{
			$codes = array
			(
			'301' => 'Moved Permanently',
			'302' => 'Found',
			'303' => 'See Other',
			'304' => 'Not Modified',
			'305' => 'Use Proxy',
			'307' => 'Temporary Redirect'
			);

			$method = isset($codes[$method]) ? $method : '302';
			header('HTTP/1.1 '.$method.' '.$codes[$method]);
			header('Location: '.$uri);
		}

		exit('<h1>'.$method.' - '.$codes[$method].'</h1><p><a href="'.$uri.'">'.$uri.'</a></p>');
	}
}

function create_token($client_data)
{
	if (empty($client_data) || !is_array($client_data) || count($client_data)<1)
		return false;
	if (!defined('PASSPORT_KEY'))
		return false;
	$str = PASSPORT_KEY;
        //sort($client_data);
        foreach ($client_data as $key=>$val)
            $str .= '|-|'.$val;
        return md5($str);
}



function check_soapclient($client_data = array(), $client_token)
{
	$client_legitimate = false;

	$get_token = array();

	if (empty($client_data) || !is_array($client_data) || count($client_data)<1)
	{
		$client_legitimate = false;
	} else if (!defined('PASSPORT_KEY')) {
		$client_legitimate = false;
	} else {
		$get_token = create_token($client_data);
		if ($get_token === $client_token)
			$client_legitimate = true;
		else
			$client_legitimate = false;
	}

	return $client_legitimate;
}

//email格式验证
function valid_email($email)
{
	return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string) $email);
}

//tel格式验证

function valid_tel($tel)
{
	return (bool) preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/", (string) $tel);
}

/*
【身份证合法性检查程序】（计算最后一位检验码）
[ 理论 ]
18位身份证：前6位是区位码（表示区域），接下来8位是表示出生日期，接下来3位是本区域的所有当天出生的人的序列号（奇数为男，偶数为女），最后1位是整个前面17位的运算得出的校验码，算法下面有实现。
15位身份证：前6位是区位码，接下来6位是出生日期（没有19），接下来3位是当天出生的人的序列号（奇数为男，偶数为女）
15位转18位：日期前面增加19，然后得出17位，最后通过这个17位运算得到最后1位校验码
*/
function get_idcard_sign($identity)
{
	$wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
	$ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
	$sigma = '';
	for ($i = 0;$i < 17;$i++) {
	    $sigma += ((int) $identity{$i}) * $wi[$i];
	}
	return $ai[($sigma % 11)];
}

function valid_identity($identity)
{
	if( strlen($identity) == 15 )
	{
		return (bool) preg_match("^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$", (string) $identity);
	}
	elseif( strlen($identity) == 18 )
	{
		return (bool) preg_match("^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$", (string) $identity);
	}
	else
	{
		return false;
	}
}



//检测用户名是否合法
function member_legitimate($username)
{
	return preg_match('/^[A-Za-z][A-Za-z0-9_]{3,17}/', $username);
}


function crypt_encode($data,$key)
{
	$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_NOFB);

	mt_srand();
	$iv = mcrypt_create_iv($size, MCRYPT_RAND);
	$tmp = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_NOFB, $iv);
	return base64_encode($iv.$tmp);
}

function crypt_decode($data,$key)
{
	$data = base64_decode($data);
	$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_NOFB);

	$iv = substr($data, 0, $size);
	$data = substr($data, $size);

	return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_NOFB, $iv), "\0");
}

function crc($u, $n = 20)
{
	$u = strtolower($u);
	$id = sprintf("%u", crc32($u));
	$m = intval(fmod($id, $n));
	return $m;
}


/*
* 创建目录树
* @param dir String   路径
* @param mode Integer 目录权限
* return bool 是否创建成功
**/
function mkdirs($dir, $mode = 0777) {
        if (!is_dir($dir)) {
            mkdirs(dirname($dir), $mode);
            return mkdir($dir, $mode);
        }
        return TRUE;
}


function dump($data) {
    echo '<pre>';
    var_dump($data);
}

// xml编码
function xml_encode($data,$encoding='utf-8',$root="data") {
    $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>\r\n";
    $xml.= "<{$root}>\r\n";
    $xml.= data_to_xml($data);
    $xml.= "</{$root}>\r\n";
    return $xml;
}

function data_to_xml($data, $level = 1) {
    if(is_object($data)) {
        $data = get_object_vars($data);
    }
    $space = str_repeat("\t", $level);
    $xml = '';
    foreach($data as $key=>$val) {
        is_numeric($key) && $key="rows";
        $xml .= $space . "<$key>";
        $xml .= $level == 1 ? "\r\n" : '';
        $xml.=(is_array($val)||is_object($val))?data_to_xml($val, $level + 1) : $val;
        list($key,)=explode(' ',$key);
        $xml .= ($level == 1 ? $space : ''). "</$key>\r\n";
    }
    return $xml;
}

// 生成随机码
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

function curl_get_contents($url = '', $method = "GET", $data = array()) {
    $query  = array();
    $curl   = curl_init();
    foreach($data as $k=>$v){
        $query[] = $k.'='.urlencode($v);
    }
    if(strtoupper($method) == 'GET' && $data){
        $url .= '?'.implode('&', $query);
    }elseif(strtoupper($method) == 'POST' && $data){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, implode('&', $query));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

// 加载配置文件
function loadConfig($str){
    require INCLUDE_PATH.'system.php';
    static $_sConfig = array();
    if(strpos($str, '.') !== false){
        list($name, $key) = explode('.', $str);
    }else{
        $name = $str;
    }

    if(!isset($_sConfig[$name])){
        include INCLUDE_PATH.'config'.DS.$systemLang['lang'].DS.'config.common.php';
        if(isset($config[$name])){
        	$_sConfig[$name] = $config[$name];
        }else{
        	$data =  include INCLUDE_PATH.'config'.DS.$systemLang['lang'].DS.'config.'.$name.'.php';
        	if($data === 1){
        		$_sConfig[$name] = $config;
        	}else{
        		$_sConfig[$name] = $data;
        	}
        }
    }
    return empty($key) ? $_sConfig[$name] : $_sConfig[$name][$key];
}


function loadModel($module_name = 'Model'){
    static $modules = array();
    if(!isset($modules[$module_name])){
        if( ! class_exists($module_name) ){
            include MODELS_PATH.$module_name.'.php';
        }
        $modules[$module_name] = new $module_name();
    }
    return $modules[$module_name];
}


function write_cache($file, $contents, $mod = 'w'){
    $fp = fopen($file, $mod);
    flock($fp, LOCK_EX);
    fwrite($fp, $contents);
    flock($fp, LOCK_UN);
    fclose($fp);
}

/**
* 发送邮件
* @params email string 目标邮箱
* @param subject string 邮件主题
* @param message string 邮件内容
*/
function send_email($email, $subject, $message){
    static $smtp;
    if(!$smtp){
        require_once (VENDORS_PATH .'swift'.DS. 'Swift.php');
        require (VENDORS_PATH .'swift'.DS.'Swift'.DS.'Connection'.DS. 'SMTP.php');
    }
    $config = loadConfig('email');
    // 创建smtp连接
    $smtp = new Swift_Connection_SMTP($config['smtp_host'], $config['smtp_port']);
    // 设置邮箱账号
    $smtp->setUsername($config['username']);
    // 设置邮箱登陆密码
    $smtp->setPassword($config['userpass']);
    $swift = new Swift($smtp);
    $s_msg = new Swift_Message($subject, $message, 'text/html', 'base64');
    try {
        return $swift->send($s_msg, $email, new Swift_Address($config['admin_email'], $config['admin_name']));
    } catch (Swift_ConnectionException $e) {
        echo 'There was a problem communicating with SMTP: ' . $e->getMessage();
        exit;
    }
}

/**
 * 获取游戏类型
 * @param string $type
 */
function getGameType($type="zh_cn"){
	$gameTypeModle = loadModel('g5_game_type');
	$types = $gameTypeModle->getAll('*');
	$list = array();
	foreach($types as $val){
		$typeId = $val['fgametypeid'];
		$name = '';
		switch($type){
			case 'zh_cn':
				$name = $val['fname'];
				break;
			case 'en_es':
				$name = $val['fname_en'];
				break;
			case 'ko':
				$name = $val['fname_ko'];
				break;
			case 'jp':
				$name = $val['fname_jp'];
				break;
			case 'tw':
				$name = $val['fname_tw'];
				break;
			default:
				$name = $val['fname'];
				break;
		}
		$list[$typeId] = $name;
	}
	return $list;
}

function getGameCompany(){
	$gameCompanyModle = loadModel('g5_game_company');
	$types = $gameCompanyModle->getAll('company_id,name');
	$list = array();
	foreach($types as $val){
		$list[$val['company_id']]= $val['name'];
	}
	return $list;
}

//广告文件外部部署
function uploadIMG($file,$type = 'png',$app ='trip')
{
	echo IMG_UPLOAD_URL."upload.php?app=".$app."&mime=".$type;die;
    $fp = curl_init();
    curl_setopt($fp, CURLOPT_URL, IMG_UPLOAD_URL."upload.php?app=".$app."&mime=".$type); //&zoom=resize_132_320
    curl_setopt($fp, CURLOPT_HEADER, 0);
    curl_setopt($fp, CURLOPT_POST, 1);
    curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($fp, CURLOPT_POSTFIELDS, base64_encode(file_get_contents($file)));

    $rtn = curl_exec($fp);
    if(curl_errno($fp))
    {
        $rs = "保持文件失败".  curl_error($fp);
    }
    else
    {
        $obj = json_decode($rtn,true);
        if($obj['code'] == 0)
        {
            $ret['url'] = $obj['url'];
        }
        else
        {
           $rs = "保持文件失败".$rtn;
        }
    }
    curl_close($fp);
    if(isset($ret['url']))
    {
        $ret['code'] = 0;
    }
    else
    {
        $ret['code'] = 100;
        $ret['msg'] = $rs;
    }
    return $ret;
}



function uploadIMGByPicasso($file)
{
	$tokenKey    = 'sjzs_video';
	$tokenSecret = 'f72dbddcac5fd0e7';
	$imgstream = file_get_contents($file);
	
	$client = new Picasso_Client($tokenKey,$tokenSecret);
	$client->addRule("1" );
	


		for($i=0;$i<5;$i++)
		{
			$res = $client->proc($imgstream);
			#print_r($res);
			if($res['ERRORMSG']=='success') break;
			sleep(1);
		}

		$img_url=$res['DATA'][1]['URL'][0];
		$img_url=str_replace('http://img.coolsrv.com/', '', $img_url);

	
	return $img_url;
}

function create_csv($data,$fileName=''){
		if($fileName==''){
			$fileName= date('Y-m-d');
		}
		$str = '';
		foreach($data as $vo){
			$str .= implode(",",$vo)."\r\n";
		}
		header('Content-Type: application/download');
		header("Content-type: text/csv");
		header("content-Disposition:filename={$fileName}.csv");
		$str =iconv('utf-8','gb2312',$str);//转换编码
		echo $str;
		die();
}


function saveLog($message)
{
    $time = date('Y-m-d H:i:s');

    file_put_contents('sign.log', $time. '--'. $message. "\n", FILE_APPEND);
}
